<template>
  <view class="add-feedback-container">
    <!-- 头部 -->
    <view class="header">
      <view class="header-left" @click="goBack">
        <text class="back-icon">←</text>
      </view>
      <text class="title">添加反馈</text>
      <view class="header-right"></view>
    </view>

    <!-- 表单内容 -->
    <view class="form-container">
      <!-- 反馈对象选择 -->
      <view class="form-section">
        <view class="section-title">
          <text class="title-text">反馈对象</text>
          <text class="required">*</text>
        </view>
        <picker 
          :value="pickerIndex" 
          :range="adminNames" 
          @change="onAdminChange"
        >
          <view class="admin-selector">
            <text v-if="selectedAdmin" class="selected-admin">{{ selectedAdmin.realName }}</text>
            <text v-else class="placeholder">请选择反馈对象</text>
            <text class="arrow">></text>
          </view>
        </picker>
      </view>

      <!-- 反馈内容 -->
      <view class="form-section">
        <view class="section-title">
          <text class="title-text">反馈内容</text>
          <text class="required">*</text>
        </view>
        <textarea 
          v-model="feedbackContent"
          class="content-textarea"
          placeholder="请详细描述您的问题或建议..."
          maxlength="500"
          :show-count="true"
        />
      </view>

      <!-- 图片上传 -->
      <view class="form-section">
        <view class="section-title">
          <text class="title-text">相关图片</text>
          <text class="optional">(可选)</text>
        </view>
        <view class="image-upload">
          <view class="image-list">
            <view 
              v-for="(image, index) in uploadedImages" 
              :key="index" 
              class="image-item"
            >
              <image :src="image" class="uploaded-image" mode="aspectFill" />
              <view class="delete-btn" @click="removeImage(index)">
                <text class="delete-icon">×</text>
              </view>
            </view>
            <view v-if="uploadedImages.length < 3" class="upload-btn" @click="chooseImage">
              <text class="upload-icon">+</text>
              <text class="upload-text">添加图片</text>
            </view>
          </view>
          <text class="upload-tip">最多可上传3张图片，支持jpg、png格式</text>
        </view>
      </view>
    </view>

    <!-- 提交按钮 -->
    <view class="submit-section">
      <button 
        class="submit-btn" 
        :class="{ disabled: !canSubmit }"
        :disabled="!canSubmit"
        @click="submitFeedback"
      >
        <text v-if="submitting" class="btn-text">提交中...</text>
        <text v-else class="btn-text">提交反馈</text>
      </button>
    </view>

  </view>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import request from '@/utils/request.js'
import tokenManager from '@/utils/token.js'

export default {
  name: 'AddFeedback',
  setup() {
    const feedbackContent = ref('')
    const selectedAdmin = ref(null)
    const uploadedImages = ref([])
    const adminList = ref([])
    const adminNames = ref([])
    const pickerIndex = ref(0)
    const submitting = ref(false)

    // 计算是否可以提交
    const canSubmit = computed(() => {
      return selectedAdmin.value && 
             feedbackContent.value.trim().length > 0 && 
             !submitting.value
    })

    // 获取管理员列表
    const fetchAdminList = async () => {
      try {
        console.log('开始获取管理员列表...')
        const response = await request.request({
          url: '/feedback/admin-names',
          method: 'GET'
        })

        console.log('管理员列表响应:', response)
        if (response.code === 200) {
          adminList.value = response.data || []
          adminNames.value = adminList.value.map(admin => admin.realName || admin.name || '未知管理员')
          console.log('管理员列表数据:', adminList.value)
          console.log('管理员名称数组:', adminNames.value)
        } else {
          console.error('获取管理员列表失败:', response)
          adminList.value = []
          adminNames.value = []
          uni.showToast({
            title: '获取管理员列表失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('获取管理员列表错误:', error)
        adminList.value = []
        adminNames.value = []
        uni.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      }
    }


    // 管理员选择变化
    const onAdminChange = (e) => {
      const index = e.detail.value
      console.log('选择的管理员索引:', index)
      console.log('当前管理员列表:', adminList.value)
      
      if (adminList.value && adminList.value.length > index) {
        selectedAdmin.value = adminList.value[index]
        pickerIndex.value = index
        console.log('选中的管理员:', selectedAdmin.value)
      } else {
        console.error('无效的管理员索引:', index)
        uni.showToast({
          title: '选择失败，请重试',
          icon: 'none'
        })
      }
    }

    // 选择图片
    const chooseImage = () => {
      const remainingCount = 3 - uploadedImages.value.length
      if (remainingCount <= 0) {
        uni.showToast({
          title: '最多只能上传3张图片',
          icon: 'none'
        })
        return
      }

      uni.chooseImage({
        count: remainingCount,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePaths = res.tempFilePaths
          uploadImages(tempFilePaths)
        },
        fail: (error) => {
          console.error('选择图片失败:', error)
          uni.showToast({
            title: '选择图片失败',
            icon: 'none'
          })
        }
      })
    }

    // 上传图片
    const uploadImages = async (filePaths) => {
      const uploadPromises = filePaths.map(filePath => {
        return new Promise((resolve, reject) => {
          uni.uploadFile({
            url: request.baseURL + '/upload/image',
            filePath: filePath,
            name: 'file',
            header: {
              'Authorization': 'Bearer ' + tokenManager.getToken()
            },
            success: (uploadRes) => {
              try {
                const data = JSON.parse(uploadRes.data)
                if (data.code === 200) {
                  resolve(data.data.url)
                } else {
                  reject(new Error(data.message || '上传失败'))
                }
              } catch (e) {
                reject(new Error('解析响应失败'))
              }
            },
            fail: (error) => {
              reject(error)
            }
          })
        })
      })

      try {
        uni.showLoading({ title: '上传中...' })
        const uploadedUrls = await Promise.all(uploadPromises)
        uploadedImages.value.push(...uploadedUrls)
        uni.hideLoading()
        uni.showToast({
          title: '上传成功',
          icon: 'success'
        })
      } catch (error) {
        uni.hideLoading()
        console.error('上传图片失败:', error)
        uni.showToast({
          title: '上传失败',
          icon: 'none'
        })
      }
    }

    // 删除图片
    const removeImage = (index) => {
      uploadedImages.value.splice(index, 1)
    }

    // 提交反馈
    const submitFeedback = async () => {
      if (!canSubmit.value) return

      if (!tokenManager.isLoggedIn()) {
        uni.showModal({
          title: '提示',
          content: '请先登录后再提交反馈',
          showCancel: false,
          confirmText: '去登录',
          success: (res) => {
            if (res.confirm) {
              uni.navigateTo({
                url: '/pages/login/login'
              })
            }
          }
        })
        return
      }

      submitting.value = true

      try {
        const params = {
          content: feedbackContent.value.trim(),
          adminId: selectedAdmin.value.id,
          adminRealName: selectedAdmin.value.realName,
          images: uploadedImages.value.join(',')
        }

        const response = await request.request({
          url: '/feedback/add',
          method: 'POST',
          data: params
        })

        if (response.code === 200) {
          uni.showToast({
            title: '反馈提交成功',
            icon: 'success'
          })
          
          // 延迟跳转，让用户看到成功提示
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          uni.showToast({
            title: response.message || '提交失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('提交反馈错误:', error)
        uni.showToast({
          title: '网络错误',
          icon: 'none'
        })
      } finally {
        submitting.value = false
      }
    }

    // 返回上一页
    const goBack = () => {
      uni.navigateBack()
    }

    onMounted(() => {
      fetchAdminList()
    })

    return {
      feedbackContent,
      selectedAdmin,
      uploadedImages,
      adminNames,
      pickerIndex,
      submitting,
      canSubmit,
      onAdminChange,
      chooseImage,
      removeImage,
      submitFeedback,
      goBack
    }
  }
}
</script>

<style scoped>
.add-feedback-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  background-color: white;
  border-bottom: 2rpx solid #f0f0f0;
}

.header-left, .header-right {
  width: 80rpx;
  display: flex;
  justify-content: center;
}

.back-icon {
  font-size: 36rpx;
  color: #333;
  font-weight: bold;
}

.title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.form-container {
  padding: 30rpx;
}

.form-section {
  background-color: white;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.section-title {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.title-text {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.required {
  color: #ff4757;
  font-size: 24rpx;
  margin-left: 4rpx;
}

.optional {
  color: #999;
  font-size: 24rpx;
  margin-left: 4rpx;
}

.admin-selector {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 8rpx;
  background-color: #fafafa;
}

.selected-admin {
  font-size: 26rpx;
  color: #333;
}

.placeholder {
  font-size: 26rpx;
  color: #999;
}

.arrow {
  font-size: 24rpx;
  color: #999;
}

.content-textarea {
  width: 100%;
  min-height: 200rpx;
  padding: 20rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 8rpx;
  font-size: 26rpx;
  color: #333;
  background-color: #fafafa;
  box-sizing: border-box;
}

.image-upload {
  margin-top: 20rpx;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  margin-bottom: 20rpx;
}

.image-item {
  position: relative;
  width: 160rpx;
  height: 160rpx;
}

.uploaded-image {
  width: 100%;
  height: 100%;
  border-radius: 8rpx;
}

.delete-btn {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  width: 40rpx;
  height: 40rpx;
  background-color: #ff4757;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.delete-icon {
  color: white;
  font-size: 24rpx;
  font-weight: bold;
}

.upload-btn {
  width: 160rpx;
  height: 160rpx;
  border: 2rpx dashed #ccc;
  border-radius: 8rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #fafafa;
}

.upload-icon {
  font-size: 48rpx;
  color: #999;
  margin-bottom: 8rpx;
}

.upload-text {
  font-size: 22rpx;
  color: #999;
}

.upload-tip {
  font-size: 22rpx;
  color: #999;
}

.submit-section {
  padding: 30rpx;
  background-color: white;
  margin-top: 20rpx;
}

.submit-btn {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
  border-radius: 12rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
}

.submit-btn.disabled {
  background: #ccc;
}

.btn-text {
  color: white;
  font-size: 28rpx;
  font-weight: bold;
}
</style>
